package com.bitoon.basketdudes.web.interceptors;

import com.bitoon.basketdudes.web.jpa.UsuarioLogin;
 
import com.opensymphony.xwork2.*;
import com.opensymphony.xwork2.interceptor.I18nInterceptor;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.opensymphony.xwork2.util.ValueStack;
import java.util.*;

import org.apache.log4j.Logger;

@Deprecated
public class LoginUsuarioLogin implements Interceptor {

    private Logger log = Logger.getLogger(LoginUsuarioLogin.class);

    public void destroy() {
    }

    public void init() {
    }

    public String intercept(ActionInvocation actionInvocation) throws Exception {
        //ActionContext actionContext = actionInvocation.getInvocationContext();
        //Map session = actionContext.getSession();
        Map session = ActionContext.getContext().getSession();

        ValueStack valueStack = ActionContext.getContext().getValueStack();
        Boolean logado = estaLogado(session);
        valueStack.set("stackLogado", logado);
        if (logado) {
            valueStack.set("stackCabecera", "cabecera_con_id.jsp");
            valueStack.set("stackUserId", dameIdUsuarioLogado(session));
            valueStack.set("stackUserLogado", dameUsuarioLogado(session));
        } else {
            valueStack.set("stackCabecera", "cabecera_sin_id.jsp");
        }

        if (log.isDebugEnabled()) {
            log.debug("i18n - Leyendo bd_lang de sesion: " + (String)session.get("bd_lang"));
        }

        if (session.containsKey("bd_lang")) {
            ActionContext.getContext().setLocale(new Locale((String)session.get("bd_lang")));
        } else {
            session.put("bd_lang", ActionContext.getContext().getLocale().getLanguage());
            session.put(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE, ActionContext.getContext().getLocale().getLanguage());
        }

        return actionInvocation.invoke();

    }

    private boolean estaLogado(Map session) {
        boolean retorno = false;
        log.debug("interceptor [1]");
        if (session.containsKey("bd_userId")) {
            if ( (Integer.parseInt((String)session.get("bd_userId"))) > 0) {
                retorno = true;
                log.debug("interceptor [2]");
            }
        }

        return retorno;
    }

    private String dameIdUsuarioLogado(Map session) {
        String retorno = "";

        if (session.containsKey("bd_userId")) {
            retorno = (String)session.get("bd_userId");
        } else {
            retorno = "0";
        }

        return retorno;
    }

    private UsuarioLogin dameUsuarioLogado(Map session) {
        UsuarioLogin retorno = null;

        if (session.containsKey("bd_userLogado")) {
            retorno = (UsuarioLogin)session.get("bd_userLogado");
        } 

        return retorno;
    }

}
